package com.qdlc.p2p.biz.util.itext;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

public class PdfHelper {

    private Document document;
    private BaseFont bfChinese;
    @SuppressWarnings("unused")
    private Font font;
    
    PdfWriter writer;

    public PdfHelper(String path) {
        document = new Document();
        try {
            writer = PdfWriter.getInstance(document, new FileOutputStream(path));// 建立一个PdfWriter对象
            document.open();
            bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 设置中文字体
            font = new Font(bfChinese, 10, Font.NORMAL);// 设置字体大小
        } catch (DocumentException de) {

        } catch (IOException ioe) {

        }
    }

    public static PdfHelper instance(String path) {
        return new PdfHelper(path);
    }

    public void exportPdf() {
        document.close();
    }

    public void addHtmlList(List<Element> list) throws DocumentException {
        for (Element e : list) {
            document.add(e);
        }
    }
    
    public void setSignaturePath(String path){
    	try {
			Image img = Image.getInstance(path);
			img.setAbsolutePosition(100, 570);
            img.setAlignment(Image.LEFT | Image.TEXTWRAP);
            img.scaleToFit(120, 120);//大小
            img.setRotationDegrees(-30);//旋转
			writer.setPageEvent(new PdfSignaturePageEventHelper(img));
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    
    /**
     * 功能描述:  PDF 每页盖章图样
     * @author linya
     * @date 2016-5-13
     */
    private class PdfSignaturePageEventHelper extends PdfPageEventHelper{
    	
    	Image image;
    	
    	PdfSignaturePageEventHelper(Image image){
    		this.image = image;
    	}
    	
    	public void onEndPage(PdfWriter writer,Document document){
    		try {
				document.add(image);
				System.out.println("++++ curent page:" + document.getPageNumber());
			} catch (DocumentException e) {
				e.printStackTrace();
			}
    	}
    }
    
}
